package com.zf.zfed.audit

import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.pdf.PdfRenderer
import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.zf.zfed.audit.databinding.ActivityPdfViewerBinding
import com.zf.zfed.audit.tools.extension.singleClick
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

/**
 * PDF阅读器Activity
 * 使用Android系统自带的PdfRenderer实现PDF文档的阅读功能
 */
class PdfViewerActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityPdfViewerBinding
    private var pdfRenderer: PdfRenderer? = null
    private var currentPage: PdfRenderer.Page? = null
    private var currentPageIndex = 0
    private var totalPages = 0
    private var pdfFileName = "用户手册.pdf"
    private var bitmap: Bitmap? = null
    private var currentScale = 1.0f
    private var matrix = Matrix()
    
    // 手势检测器
    private lateinit var gestureDetector: GestureDetector

    private lateinit var scaleGestureDetector: ScaleGestureDetector
    private var isScaling = false
    
    // 连续滚动相关
    private var allPagesBitmap: Bitmap? = null
    private var scrollOffset = 0f
    private var isDragging = false
    private var lastTouchY = 0f
    
    companion object {
        const val EXTRA_PDF_NAME = "pdf_name"
        const val EXTRA_PDF_PATH = "pdf_path"
        private const val MIN_SCALE = 0.5f
        private const val MAX_SCALE = 3.0f
        private const val SCALE_FACTOR = 1.2f
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPdfViewerBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 获取传递的参数
        pdfFileName = intent.getStringExtra(EXTRA_PDF_NAME) ?: "用户手册.pdf"
        
        setupGestureDetectors()
        loadPdf()
    }
    
    /**
     * 设置手势检测器
     */
    private fun setupGestureDetectors() {
        // 设置滑动手势检测器
        gestureDetector = GestureDetector(this, object : GestureDetector.OnGestureListener {
            override fun onDown(e: MotionEvent): Boolean {
                lastTouchY = e.y
                isDragging = true
                return true
            }
            
            override fun onShowPress(e: MotionEvent) {}
            
            override fun onSingleTapUp(e: MotionEvent): Boolean {
                // 点击切换页面（保持原有功能）
                if (currentPageIndex < totalPages - 1) {
                    showPage(currentPageIndex + 1)
                } else {
                    showPage(0) // 回到第一页
                }
                return true
            }
            
            override fun onScroll(
                e1: MotionEvent,
                e2: MotionEvent,
                distanceX: Float,
                distanceY: Float
            ): Boolean {
                if (isScaling) return false
                
                // 实现平滑滚动
                scrollOffset += distanceY
                updateScrollPosition()
                return true
            }
            
            override fun onLongPress(e: MotionEvent) {}
            
            override fun onFling(
                e1: MotionEvent,
                e2: MotionEvent,
                velocityX: Float,
                velocityY: Float
            ): Boolean {
                if (isScaling) return false
                
                // 惯性滚动
                val flingDistance = velocityY * 0.1f
                scrollOffset += flingDistance
                updateScrollPosition()
                return true
            }
        })
        
        // 设置缩放手势检测器
        scaleGestureDetector = ScaleGestureDetector(this, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
            override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
                isScaling = true
                return true
            }
            
            override fun onScale(detector: ScaleGestureDetector): Boolean {
                val scaleFactor = detector.scaleFactor
                val newScale = currentScale * scaleFactor
                
                if (newScale >= MIN_SCALE && newScale <= MAX_SCALE) {
                    currentScale = newScale
                    updateScrollPosition()
                }
                return true
            }
            
            override fun onScaleEnd(detector: ScaleGestureDetector) {
                isScaling = false
            }
        })
        
        // 设置触摸事件监听
        binding.pdfView.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    isDragging = false
                }
            }
            scaleGestureDetector.onTouchEvent(event)
            gestureDetector.onTouchEvent(event)
            true
        }
    }
    
    /**
     * 更新滚动位置
     */
    private fun updateScrollPosition() {
        if (allPagesBitmap != null) {
            // 限制滚动范围
            val maxScroll = (allPagesBitmap!!.height * currentScale) - binding.pdfView.height
            scrollOffset = scrollOffset.coerceIn(-maxScroll, 0f)
            
            // 更新矩阵
            matrix.reset()
            matrix.postScale(currentScale, currentScale)
            matrix.postTranslate(0f, scrollOffset)
            binding.pdfView.imageMatrix = matrix
        }
    }
    
    /**
     * 加载PDF文件
     */
    private fun loadPdf() {
        try {
            binding.progressBar.visibility = View.VISIBLE
            binding.tvError.visibility = View.GONE
            
            val pdfFile = loadPdfFromAssets()
            
            if (pdfFile != null && pdfFile.exists()) {
                openPdfRenderer(pdfFile)
                createAllPagesBitmap()
            } else {
                showError("PDF文件不存在")
            }
        } catch (e: Exception) {
            e.printStackTrace()
            showError("加载PDF失败: ${e.message}")
        } finally {
            binding.progressBar.visibility = View.GONE
        }
    }
    
    /**
     * 从assets目录加载PDF文件
     */
    private fun loadPdfFromAssets(): File? {
        return try {
            val inputStream: InputStream = assets.open(pdfFileName)
            val file = File(cacheDir, pdfFileName)
            val outputStream = FileOutputStream(file)
            
            val buffer = ByteArray(1024)
            var size: Int
            while (inputStream.read(buffer).also { size = it } != -1) {
                outputStream.write(buffer, 0, size)
            }
            
            inputStream.close()
            outputStream.close()
            file
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }
    
    /**
     * 打开PDF渲染器
     */
    private fun openPdfRenderer(pdfFile: File) {
        try {
            val fileDescriptor = ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY)
            pdfRenderer = PdfRenderer(fileDescriptor)
            totalPages = pdfRenderer?.pageCount ?: 0
        } catch (e: Exception) {
            e.printStackTrace()
            throw e
        }
    }
    
    /**
     * 创建所有页面的合并位图
     */
    private fun createAllPagesBitmap() {
        if (pdfRenderer == null || totalPages == 0) return
        
        try {
            // 计算总高度
            var totalHeight = 0
            val pageWidths = mutableListOf<Int>()
            val pageHeights = mutableListOf<Int>()
            
            // 先获取所有页面的尺寸
            for (i in 0 until totalPages) {
                val page = pdfRenderer?.openPage(i)
                if (page != null) {
                    pageWidths.add(page.width)
                    pageHeights.add(page.height)
                    totalHeight += page.height
                    page.close()
                }
            }
            
            // 使用最大宽度
            val maxWidth = pageWidths.maxOrNull() ?: 0
            
            // 创建合并位图
            allPagesBitmap?.recycle()
            allPagesBitmap = Bitmap.createBitmap(maxWidth, totalHeight, Bitmap.Config.ARGB_8888)
            
            // 渲染所有页面到合并位图
            var currentY = 0
            for (i in 0 until totalPages) {
                val page = pdfRenderer?.openPage(i)
                if (page != null) {
                    val pageBitmap = Bitmap.createBitmap(page.width, page.height, Bitmap.Config.ARGB_8888)
                    page.render(pageBitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
                    
                    // 将页面位图绘制到合并位图上
                    val canvas = android.graphics.Canvas(allPagesBitmap!!)
                    canvas.drawBitmap(pageBitmap, 0f, currentY.toFloat(), null)
                    
                    currentY += page.height
                    pageBitmap.recycle()
                    page.close()
                }
            }
            
            // 显示合并位图
            displayAllPagesBitmap()
            
        } catch (e: Exception) {
            e.printStackTrace()
            showError("创建页面位图失败: ${e.message}")
        }
    }
    
    /**
     * 显示所有页面位图
     */
    private fun displayAllPagesBitmap() {
        if (allPagesBitmap != null) {
            binding.pdfView.setImageBitmap(allPagesBitmap)
            
            // 应用缩放和滚动
            matrix.reset()
            matrix.postScale(currentScale, currentScale)
            matrix.postTranslate(0f, scrollOffset)
            binding.pdfView.imageMatrix = matrix
        }
    }
    
    /**
     * 显示指定页面（保留用于点击翻页）
     */
    private fun showPage(index: Int) {
        // 关闭当前页面
        currentPage?.close()
        
        // 检查索引有效性
        if (index < 0 || index >= totalPages) {
            return
        }
        
        try {
            // 打开新页面
            currentPage = pdfRenderer?.openPage(index)
            currentPageIndex = index
            
            // 创建位图
            bitmap?.recycle()
            bitmap = Bitmap.createBitmap(
                currentPage?.width ?: 0,
                currentPage?.height ?: 0,
                Bitmap.Config.ARGB_8888
            )
            
            // 渲染页面
            currentPage?.render(bitmap!!, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
            
            // 显示位图
            displayBitmap()

            // 重置ScrollView到顶部
            binding.pdfView.parent?.let { parent ->
                if (parent is android.widget.ScrollView) {
                    parent.scrollTo(0, 0)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            showError("渲染页面失败: ${e.message}")
        }
    }
    
    /**
     * 显示位图
     */
    private fun displayBitmap() {
        if (bitmap != null) {
            // 设置原始位图
            binding.pdfView.setImageBitmap(bitmap)
            
            // 应用缩放矩阵
            matrix.reset()
            matrix.postScale(currentScale, currentScale)
            binding.pdfView.imageMatrix = matrix
        }
    }

    /**
     * 显示错误信息
     */
    private fun showError(message: String) {
        binding.progressBar.visibility = View.GONE
        binding.tvError.visibility = View.VISIBLE
        binding.tvError.text = message
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 清理资源
        currentPage?.close()
        pdfRenderer?.close()
        bitmap?.recycle()
        allPagesBitmap?.recycle()
    }
}